package com.example.birdfriends.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.example.birdfriends.pojo.export.vo.DataExportVo;
import com.example.birdfriends.service.DataExportReadService;
import com.example.birdfriends.service.DataExportWriteService;
import com.example.birdfriends.utils.export.DataExportScheduleTask;
import com.example.birdfriends.utils.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Map;

@RestController
@RequestMapping("/dataExport")
public class DataExportController {
    private static final Logger logger = LoggerFactory.getLogger(DataExportController.class);
    @Autowired
    private DataExportReadService dataExportReadService;
    @Autowired
    private DataExportWriteService dataExportWriteService;
    @Autowired
    private DataExportScheduleTask dataExportScheduleTask = null;
    @Autowired
    private Result result = null;

    private static final String ROOT_PATH = "/D://bf-files/springboot-upload/export-files";
    private String dataTable;
    private String exportTime;

    // D:/bf-files/springboot-upload/export-files/20240312/birds/20ac66c6efc04207bf801b0523c6c7a6.xlsx
    @PostMapping("dataExportToExcel")
    public Map<String, Object> dataExportToExcel(@RequestBody DataExportVo dataExportVo, HttpSession session){
        String fileVirtualPath = "http://localhost:8888/export-files/";
        System.out.print("export data vo:");dataExportVo.print();
        try{
            dataTable = dataExportVo.getExportTable();
            dataExportWriteService.addDataExport(dataExportVo);
            dataExportScheduleTask.scheduledTaskByConfig(session);
            String filePath = (String) session.getAttribute(dataExportVo.getExportTable());

            String[] filePathArr = filePath.split("/");
            exportTime = filePathArr[filePathArr.length-3];

            fileVirtualPath = fileVirtualPath + filePathArr[filePathArr.length-3] +'/' + filePathArr[filePathArr.length-2] + '/' + filePathArr[filePathArr.length-1];
            return result.resultMap(true, "文件导出成功", fileVirtualPath);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("数据导出任务创建失败");
            return result.resultMap(false, "文件导出失败", fileVirtualPath);
        }
    }
}
